package com.dss.auto_deploy.util.converter;

import com.dss.auto_deploy.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author dongshoushan
 * @date 2020年07月07日 18:20
 */
@Slf4j
public class BaseConverter<T, VO> {
    public VO convert(T source, Class<VO> targetClazz) {
        VO target = null;
        try {
            target = targetClazz.newInstance();
            if (Objects.isNull(source)) {
                return target;
            }
            convert(source, target);
        } catch (Exception e) {
            log.error("初始化{}对象失败", targetClazz, e);
        }

        return target;
    }
    /**
     * entity批量转换为VO
     *
     * @param sourceList
     * @param clazz
     * @return
     */
    public List<VO> convert(List<T> sourceList, Class<VO> clazz) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return new ArrayList<>();
        }
        return sourceList.stream()
                .map((e -> convert(e, clazz)))
                .collect(Collectors.toList());
    }

    /**
     * 属性copy，处理特殊需求时子类复写该方法
     *
     * @param source
     * @param target
     */
    protected void convert(T source, VO target){
        BeanUtils.copyProperties(source, target);
    }
}
